import babelpolyfill from 'babel-polyfill'
import Vue from 'vue'
import App from './App'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
//import './assets/theme/theme-green/index.css'
import VueRouter from 'vue-router'
import store from './vuex/store'
import Vuex from 'vuex'
//import NProgress from 'nprogress'
//import 'nprogress/nprogress.css'
import routes from './routes'
// import Mock from './mock'
// Mock.bootstrap();
import 'font-awesome/css/font-awesome.min.css'
// 引入axios
import axios from "axios";
// 设置基础请求路径
axios.defaults.baseURL = "http://bugtracker.itsource.cn:8080/"
// 设置vue的扩展属性
Vue.prototype.$http = axios

Vue.use(ElementUI)
Vue.use(VueRouter)
Vue.use(Vuex)

//NProgress.configure({ showSpinner: false });

const router = new VueRouter({
    routes
})

// =============前端拦截器开始======================
// 路由拦截器
router.beforeEach((to, from, next) => {
    console.log("11111111111111");
    if (to.path == '/login' || to.path == '/shopRegister' ||to.path == '/shop/activite/98') {
        localStorage.removeItem('token');
        localStorage.removeItem('logininfo');
        next();
    } else {
        let user = JSON.parse(localStorage.getItem('logininfo'));
        if (user) {
            next();
        } else {
            next({path: '/login'})
        }
    }
})

//2.配置axios前置拦截器，作用是让所有axios请求携带token，后台需要token校验是否登录
axios.interceptors.request.use(config => {
    console.log("222222222");
    // 2.1.从缓存中获取到token
    let token = localStorage.getItem("token");
    // 2.2.如果token不为null，那么设置到请求头中，此处哪怕为null，我们也不进行处理，因为后台会进行拦截
    if (token) {
        config.headers['token'] = token;
    }
    // 2.3.放行
    return config;
}, error => {
    Promise.reject(error);
})

//3.配置axios后置拦截器，作用是为了得到后端的拦截器响应结果
//  前端需要知道用户是否登录，如果响应是success=false&resultObj=noLogin那么说明用户未登录，直接跳转到登录页面
axios.interceptors.response.use(result => {
    console.log("333333333");
    // 3.1.获取到后端的响应结果
    let data = result.data;
    // 3.2.判断如果后端响应是success=false&resultObj=noLogin，那就说明在后端拦截器中被拦截下来了，那么跳转到登录页面
    if (!data.success && data.resultObj === "noLogin") {
        // 跳转登录页面
        router.push({path: '/login'});
    }
    // 3.3.放行
    return result;
}, error => {
    Promise.reject(error);
})
// ===================前端拦截器结束===============================

new Vue({
    //el: '#app',
    //template: '<App/>',
    router,
    store,
    //components: { App }
    render: h => h(App)
}).$mount('#app')